package com.eric.nioclient.service.packet;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;

public class PacketDecoder extends LengthFieldBasedFrameDecoder {

	public PacketDecoder(int maxFrameLength, int lengthFieldOffset,
                         int lengthFieldLength, int lengthAdjustment,
						 int initialBytesToStrip) {
		super(maxFrameLength, lengthFieldOffset, lengthFieldLength, lengthAdjustment,
				initialBytesToStrip);
	}

	public Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
		ByteBuf frame = (ByteBuf) super.decode(ctx, in);
		if(frame.readableBytes() <= 0) return null ;

		int packetType = frame.readInt();
		int length = frame.readInt();
		System.out.println("package Type :"+packetType+"  length:"+length);
		Packet packet = PacketType.getPacketClassBy(packetType).newInstance();
		packet.readFromBuff(frame);

		return packet;
	}

}